let columns = []
let myDatas = []
let date = [
    {
        field : 'checked',
        checkbox : true,
        //跟据返回每行的数据
        formatter :function(value,row,index){
            return '';
        }
    },
    {
        field: 'name',
        title: '姓名'
    },
    {
        field: 'mobile',
        title: '手机号'
    },
    {
        field: 'studentId',
        title: '工号/学号'
    },
    {
        field: 'college',
        title: '院系'
    },
    {
        field: 'major',
        title: '专业'
    },
    {
        field: 'grade',
        title: '年级'
    },
    {
        field: 'administrativeClass',
        title: '行政班'
    },
    {
        field: 'gmtCreate',
        title: '注册时间'
    },
    {
        field: 'gmtModified',
        title: '更新时间'
    },
    {
        title: '操作',
        field: 'userName',
        formatter: function (value, row, index) {

            let mydiv=''

            if(myAuthority.resetPSW){
                mydiv+=` <a class="btn-color" href="#" mce_href="#" title="重置密码" onclick="congzhiedit(${index})">重置密码</a>`
            }
            if(myAuthority.lookInfor){
                mydiv+=`<a class="btn-color" href="#" mce_href="#" title="详情" onclick="xiangqing(${index})">详情</a>`
            }
            if(myAuthority.edit){
                mydiv+=`<a class="btn-color" href="#" mce_href="#" title="编辑" onclick="edit(${index})">编辑</a>`
            }
            if(myAuthority.del){
                mydiv+=`  <a class="btn-color" href="#" title="删除"  mce_href="#" onclick="deletes(${index})">删除</a>`
            }

            return mydiv;
        }
    }
]
let pageNum = 1, pageSize = 10;
let myAuthority={
    add:false,
    edit:false,
    select:false,
    del:false,
    lookInfor:false,
    resetPSW:false
}


$(function () {
    myAuthority.add = $('#authorityButtonAdd').val()?JSON.parse($('#authorityButtonAdd').val()):false
    myAuthority.edit = $('#authorityButtonEdit').val()?JSON.parse($('#authorityButtonEdit').val()):false
    myAuthority.select = $('#authorityButtonInquire').val()?JSON.parse($('#authorityButtonInquire').val()):false
    myAuthority.del = $('#authorityButtonDelete').val()?JSON.parse($('#authorityButtonDelete').val()):false
    myAuthority.resetPSW = $('#authorityButtonResetPSW').val()?JSON.parse($('#authorityButtonResetPSW').val()):false
    myAuthority.lookInfor = $('#authorityButtonLookInfor').val()?JSON.parse($('#authorityButtonLookInfor').val()):false

    console.log('=======myAuthority.select=',myAuthority)
    //导入
    layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        upload.render({
            elem: '#btnUpload', //绑定元素
            url: '/sysxn/user/import', //上传接口
            accept: 'file',
            done: function (r) {
                //返回判断
                if(r.code=="1"||r.code==1){
                    layer.msg(r.msg);
                }else{
                    if(r.code=="41304"){
                        layer.confirm( '是否下载错误报告?',{
                            btn1:(index)=>{
                                const a = document.createElement('a')
                                a.style.display = 'none';
                                a.target="_blank";
                                a.href = `/sysxn/user/importComError`
                                a.click()
                                layer.close(index)
                            }
                        })
                    }
                }

                reLoad()
                load()

            },
            error: function (r) {
                layer.msg(r.msg);
            }
        });
    });

    columns = date
    load();
});

function load() {
    if (myAuthority.select) {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get', // 服务器数据的请求方式 get or post
                    // url:`/famousTeacher/list/${pageNum}/${pageSize}`, // 服务器数据的加载地址
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: true, // 设置为true会有隔行变色效果
                    dataType: "json", // 服务器返回的数据类型
                    pagination: true, // 设置为true会在底部显示分页条
                    singleSelect: false, // 设置为true将禁止多选
                    // contentType : "application/x-www-form-urlencoded",
                    // //发送到服务器的数据编码类型
                    pageSize: 10, // 如果设置了分页，每页数据条数
                    pageNumber: 1, // 如果设置了分布，首页页码
                    pageList: [10, 20, 50, 100],//可选择单页记录数
                    //search : true, // 是否显示搜索框
                    showColumns: false, // 是否显示内容下拉框（选择显示的列）
                    clickToSelect:true,
                    sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                    queryParamsType: "",
                    showPaginationSwitch: false,
                    // // //设置为limit则会发送符合RESTFull格式的参数
                    queryParams: function (params) {
                        pageNum = Number(params.pageNumber)
                        pageSize = Number(params.pageSize)

                    },
                    ajax: function (params) {
                        $.ajax({
                            url: `/sysxn/user/list`,
                            data: {
                                name: $('#myname').val(),
                                mobile: $('#myphone').val(),
                                pageNumber: pageNum,
                                pageSize: pageSize
                            },
                            type: "get",
                            success: function (res) {
                                params.success(res);
                            },
                            error: function (rs) {
                                console.log(rs)
                            }
                        })
                    },

                    responseHandler: function (res) {
                        if (res.code !== '0') {
                            layer.msg(res.msg);
                            return {
                                "total": 0,//总数
                                "rows": [] //数据
                            };
                        }
                        myDatas = res.data.records
                        return {
                            "total": res.data.total,//总数
                            "rows": res.data.records  //数据
                        };

                    },
                    columns: columns
                });
    }else{
        layer.msg("请找管理员授权");
    }
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}


// 新增资源
function addResource(index) {
    switch (index) {
        case 1:
            console.log('新增数据')
            layer.open({
                type: 2,
                title: '新增用户',
                maxmin: true,
                shadeClose: false, // 点击遮罩关闭层
                area: ['1200px', '750px'],
                content: '/sysxn/user/add'// iframe的url
            });
            break;
        case 3:
            //
            var ids = $('#exampleTable').bootstrapTable('getSelections');
            console.log('===idsidsids=========',ids)
            console.log('===idsidsids=========',pageSize)
            let href="/sysxn/user/downloadUserXn"
            if(ids.length==0){
                layer.msg("请选择用户，或者全部选择")
                return;
            }
            if(pageSize==ids.length){
                href=href+"?code="+1
                console.log("全选",href)
            }else{

                let idList =[]
                    ids.forEach(item=>{
                      idList.push(item.id)
                    })
                href=href+"?idList="+idList
                console.log("单独",href)
            }
            //
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = href
            a.click()
            console.log("===>>>",$("aXZ"))

                break;

    }

}
function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}
// 删除
function deletes(index) {
    layer.confirm('确定要删除当前资源？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: `/sysxn/user/remove`,
            data:{id:myDatas[index].id},
            type: "POST",
            success:  (res)=>{
                console.log('删除', res)
                if (res.msg.indexOf('成功')>-1) {
                    //关闭
                    layer.close(layer.index)
                    reLoad()
                    load()
                }

            },
            error: function (rs) {
                console.log(rs)
                layer.close(layer.index)
            }
        })

    })
}

//重置密码
function congzhiedit(index1){
    console.log('重置密码')
    layer.open({
        type: 1,
        title:'修改密码',
        area: ['420px', '250px'], // 宽高
        btn: ['提交'],
        btnAlign:"c",
        content: `<link rel="stylesheet" href="/lib/layui/css/layui.css"> 
                   <script src="/lib/layui/layui.js"></script>
                 <div class="layui-form" style="height: 100%;width: 90%;  margin-left: 5%; display: flex; justify-content: space-evenly; flex-direction: column;">

                         <div class="layui-input-wrap" style=" margin-top: 20px; font-size: 15px;  ">
                            <input  name="newPassWord" id="newPassWord" type="password"
                                    class="layui-input" autocomplete="off" placeholder="请输入8位数新密码" lay-affix="eye"/>

                        </div>

                        <div class="layui-input-wrap" style="margin-top: 20px; font-size: 15px; ">
                            <input  name="password" id="password" type="password" class=" layui-input"
                                    autocomplete="off" placeholder="请输入您的密码" lay-affix="eye"/>
                        </div>

                        </div>
                    
                        `,
        success: function(layero, index){
            console.log('=======asasassend==')

        },
        btn1:  (index, layero)=> {
            var password = layero.find("#password").val();
            var newPassword = layero.find("#newPassWord").val();
            if (password ==""){
                layer.msg("密码不能为空")
                return false
            }
            if (password != newPassword){
                layer.msg("两次密码输入不一致，请修改后提交！")
                return false
            }
            $.ajax({
                url: "/sysxn/user/adminResetPwd",
                type:'POST',
                data: {
                    id:myDatas[index1].id,
                    password: password
                },
                success: function (r) {
                    if(r.msg.indexOf('成功')>-1){
                        //关闭
                        layer.close(index);
                        reLoad()
                        load()
                    }else{
                        layer.msg(r.msg);
                    }
                }
            })


        }
    });






}
//详情
function  xiangqing(index){
    console.log('详情')

        var index = layer.open({
            type: 2,
            title: '用户详情',
            maxmin: true,
            shadeClose: false, // 点击遮罩关闭层
            area: ['1000px', '720px'],
            content:`/sysxn/user/info/${myDatas[index].id}`
        });
        layer.full(index);

}
// 编辑资源
function edit(index) {
    const url = `/sysxn/user/edit/${myDatas[index].id}`
    console.log('编辑数据')
    layer.open({
        type: 2,
        title: '编辑',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['1200px', '750px'],
        content: url// iframe的url
    });
}






